<?php

namespace App\Http\Controllers\SubAccount;

use App\Common\Traits\Model\ModelSearchTrait;
use App\Helpers\ServiceTrait;
use App\Http\Controllers\Controller;
use App\Models\Business\RecordDataColumn;
use App\Models\ShopManager;
use App\Models\SubAccount\SubAccount;
use Illuminate\Http\Request;
use App\Jobs\SubAccount\SubAccountLoginLogoutRecordJob;
use App\Models\ShopDetail;

class SubAccountController extends Controller
{
    use ModelSearchTrait,ServiceTrait;

    //
    public function index(Request $request, SubAccount $subAccount)
    {
        SubAccountLoginLogoutRecordJob::dispatch();
        $subAccount=$this->model($subAccount,$request->user());
        $subAccount=$this->singleModelSearch($request,$subAccount,$this->subCondition());
        $subAccount=$this->relatedModelSearch($request,$subAccount,$this->relatedCondition());
        $subAccount=$this->repayConditionSearch($request,$subAccount);
        $accounts=$subAccount->with($this->listWith())->orderByDesc('updated_at')->paginate($request->size??20)->withQueryString();
        return $this->success(['accounts'=>$accounts]);
    }

    //
    public function subCondition()
    {
        return [
            ['sub_account','like'],
            ['shop_id','='],
            ['service_time_end','between'],
        ];
    }
    //
    public function relatedCondition(){
        return [
            'shop'=>[
                ['shop_name','like'],
            ]
        ];
    }
    //续费类型
    public function repayConditionSearch($request,$model){
        if($request->filled('repay_type')){
            $deadLine=date('Y-m-d H:i:s',time()+7*24*3600);
            if($request->repay_type==1){
                return $model->where('service_time_end', '>=', now())->where('service_time_end', '<=', $deadLine);
            }elseif($request->repay_type==2){
                return $model->where('service_time_end', '>=', $deadLine);
            }elseif($request->repay_type==3){
                return $model->where('status', '=', 0);
            }
        }
        return $model;
    }
    //
    public function listWith(){
        return [
            'shop:id,shop_name',
            'staff:id,username,name,phone,department_one_id,department_two_id,department_three_id',
            'department1:id,name',
            'department2:id,name',
            'department3:id,name',
        ];
    }

    //
    public function store(Request $request, SubAccount $subAccount)
    {
        $shop=ShopDetail::find($request->shop_id??0);
        if(empty($shop)){
            return $this->failed('shop_id错误',201);
        }
        if($request->filled('shop_name')){
            $this->updateShopName($request->shop_name,$shop);
        }
        $data=$this->accountData($request);
        $data=$this->addExtraInfo($data,$shop);
        if($request->sub_account_id){
            $account=$subAccount->find($request->sub_account_id);
            if(!$account){
                return $this->failed('子账号id错误，无此子账号',201);
            }
            $data['update_admin_id']=auth()->user()->id??'';
            $account->update($data);
            return $this->success(['msg'=>'编辑成功']);
        }else{
            $data['create_admin_id']=auth()->user()->id??'';
            SubAccount::create($data);

            //生成上下号记录
            SubAccountLoginLogoutRecordJob::dispatch();

            return $this->success(['msg'=>'新建成功']);
        }

    }
    //更新店铺名称
    public function updateShopName($shopName,$shop){
        if($shopName){
            $shop->shop_name=$shopName;
            return $shop->save();
        }
        return false;
    }
    //
    public function accountData($request)
    {
        return [
            'shop_id'=>$request->shop_id,
            'template_id'=>$request->template_id,
            'sub_account'=>$request->sub_account,
            'source_id'=>$request->source_id,
            'account_code'=>$request->account_code,
            'verify_phone'=>$request->verify_phone,
            'consult_quantity'=>$request->consult_quantity,
            'try_time_start'=>$request->try_time_start,
            'try_time_end'=>$request->try_time_end,
            'service_time_start'=>$request->service_time_start,
            'service_time_end'=>$request->service_time_end,
            'boss_demands'=>$request->boss_demands,
            'sub_amount'=>$request->sub_amount,
            'status'=>$request->status??1,
            'resume_at'=>$request->resume_at??null,
        ];
    }
    //
    public function addExtraInfo($data,$shop){
        $data['department1_id']=$shop->department->department1->id??null;
        $data['department2_id']=$shop->department_two_id??null;
        $data['department_id']=$shop->department_two_id??null;
        return $data;
    }

    //
    public function show(Request $request)
    {
        $subAccount=SubAccount::find($request->sub_account_id);
        $subArray=$subAccount->toArray()??[];
        $detailData=$this->details($subAccount,$subArray);
        return $this->success($detailData);
    }
    //
    public function details($subAccount,$subArray){
        $subArray['template_name']=$subAccount->template->platformType->platform_name??'';
        $subArray['source_name']=$subAccount->source->source_name??'';
        $subArray['repay_remind_time']=date('Y/m/d H:i:s',strtotime($subAccount->service_time_end)-7*24*3600);
        $subArray['company_name']=$subAccount->shop->shop->customer->company_name??'';
        $subArray['wx_group']=$subAccount->shop->wx_group??'';
        $subArray['shop_name']=$subAccount->shop->shop_name??'';
        $subArray['category_name']=$subAccount->shop->shop->object_name??'';
        $subArray['store_category']=$subAccount->shop->store_category??'';
        $subArray['platform_name']=$subAccount->shop->platform->platform_name??'';
        $subArray['department1']=$subAccount->department1->name??'';
        $subArray['department2']=$subAccount->department2->name??'';
        $subArray['department3']=$subAccount->department3->name??'';
        $subArray['staffs']=$this->getStaffNames($subAccount);

        return $subArray;
    }
    //
    public function getStaffNames($subAccount)
    {
        $names='';
        $pluckNames=$subAccount->staff()->pluck('name');
        if(count($pluckNames)){
            $names=$pluckNames->implode('，');
        }
        return $names;
    }

    //获取店铺数据登记字段
    public function dataColumnByShopId(Request $request)
    {
        $shop=ShopDetail::find($request->shop_id??0);
        if(empty($shop)){
            return $this->failed('店铺id错误，无此店铺',201);
        }
        $dataColumn=RecordDataColumn::with('platformType')->where('platform_type_id',$shop->plateform_id)->first();
        return $this->success($dataColumn);
    }

    //添加数据截图
    public function addScreenShots(Request $request){
        $account=SubAccount::find($request->sub_account_id);
        if(empty($account)){
            return $this->failed('id错误，无此子账号');
        }
        $account->data_screen_shots=$request->data_screen_shots;
        $account->save();
        return $this->success('更新成功');
    }


}
